import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class Article extends StatefulWidget {
  const Article({ super.key });

  @override
  _ArticleState createState() => _ArticleState();
}

class _ArticleState extends State<Article> {
  int pre_timestamp = DateTime.now().millisecondsSinceEpoch;
  int channelId = 0;

  List<ArticleItem> list = [];

  @override
  void initState() {
    // TODO: implement initState
    getArticleList();
    super.initState();
  }
  
  getArticleList () async {
    const baseURL = "https://toutiao.itheima.net/v1_0";
    Dio di = Dio();
    try {
      print(
        pre_timestamp
      );
       var result = await di.get("$baseURL/articles",
        queryParameters: {
          "channel_id": channelId,
          "timestamp": pre_timestamp
        }
       );
       var tempList = result.data["data"]["results"] as List;
       for (var item in tempList) {
        List<String> temp = [];
        if(item["cover"]["images"] != null) {
          for (var element in item["cover"]["images"]) {
            temp.add(element);
          }
        }
        list.add(ArticleItem(
           art_id: item["art_id"],
           aut_name: item["aut_name"],
           comm_count: item["comm_count"],
           pubdate: item["pubdate"],
           title: item["title"],
           content: item["content"],
           cover: CoverItem(type: item["cover"]["type"], images: temp) ,
           is_top: item["is_top"]
        ));
       }
       setState(() {
        //  list.addAll(result.data["data"]["results"] as List<ArticleItem>); 
       });
       
    } catch (error) {
       print(error);
    }
   
  }
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        return  ArticleItemCom(item: list[index] );
      },
      itemCount: list.length,
      );
  }
}

class ArticleItemCom extends StatefulWidget {
  final ArticleItem? item;
  const ArticleItemCom({ super.key, required this.item });
  @override
  _ArticleItemState createState() => _ArticleItemState();
}
class _ArticleItemState extends State<ArticleItemCom> {
  


  @override
  void initState() {
  
    // TODO: implement initState
    super.initState();
  }
  Widget getCoverItem (CoverItem cover) {
    if(cover.type == 0) {
      return const SizedBox(width: 0,height: 0);
    }
    else if(cover.type == 1) {
     return Image.network(cover.images![0], height: 100,);
    }
    else if(cover.type == 3) {
      Row(
        children: [
          ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return 
              Expanded(
              child: 
               Image.network(cover.images![index],
                height: 100,)
              ) ; 
            },
            itemCount: cover.images!.length,
          )
          
        ],
      ); 
    }
    return const SizedBox(width: 0,height: 0);
  }
  
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Container(
      width: size.width,
      height: 100,
      padding: const EdgeInsets.only(left: 20, top: 20),
      decoration: const BoxDecoration(
        
      ),
      child:  Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
         Text(widget.item?.title! ?? "无标题",
            style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold
          ),  
         ), 
         const SizedBox(height: 30),
         // ignore: unrelated_type_equality_checks
          // widget.item?.cover?.type != Null  ? Null : Null,
          getCoverItem(widget.item!.cover!),
         Row(
          children: [
            Text(widget.item?.aut_name ?? ""),
            const SizedBox(width: 20.0),
            Text("${widget.item?.comm_count ?? ""}评论"),
            const SizedBox(width: 20.0),
            Text(widget.item?.pubdate ?? "")
          ],
         )
        
        ]
      

      ),
      
    );
  }
}


class ResponseData<T> {
  T? data;
  String message = "";
}
class ArticleResult {
  int pre_timestamp = 0;
  List<ArticleItem> results = [];
}

class ArticleItem {
  String? content = "";
  String? art_id = "";
  String? title = "";
  String? aut_name = "";
  int? comm_count = 0;
  String? pubdate = "";
  int? is_top = 0;
  CoverItem? cover;

  ArticleItem({
  required  this.art_id,
  required this.content,
  required this.title,
  required this.aut_name,
  required this.is_top,
  required this.pubdate,
  required this.comm_count,
   this.cover
  });
  // CoverItem cover = CoverItem();
  // factory ArticleItem.fromJson(Map<String, dynamic> json) {
  //      // 根据 JSON 数据初始化 ArticleItem 对象
  //      return ArticleItem();
  //    }
}
class CoverItem {
  int? type  = 0;
  List<String>? images = [];
  CoverItem({ required this.type, required this.images });
}
enum CoverType {
  ONE,
  Three,
  ZERO
}
